package com.example.demo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@WebServlet(name = "InitSocketServlet")
public class InitSocketServlet extends HttpServlet {
    public static List<Socket> socketList = new CopyOnWriteArrayList<>();

    public InitSocketServlet(){
        System.out.println("InitSocketServlet");
    }

    @Override
    public void init() throws ServletException {
        try {
            ServerSocket serverSocket = new ServerSocket(1111);
            new Thread(){
                @Override
                public void run() {
                    while(true){
                        try {
                            Socket socket = serverSocket.accept();
                            socketList.add(socket);
                            System.out.println(socket.getRemoteSocketAddress()+"连接成功");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
